import './LogicalFieldModal.scss';
import { cloneDeep } from 'lodash';
import i18n from '@src/locales'

const LogicalFieldModal = {
  name: 'logical-field-modal',
  data(){
    return {
      show: false,
      currValue: null,
      fieldName: null,
      options: [],
      sectionState: {},
      // 可用逻辑字段
      logicalFields: [],
      groups: [], // 分组字段
    }
  },
  methods: {
    showModal(field, allFields){
      // 只能选择该字段之后的非系统字段
      this.logicalFields = this.filterLogicalFields(field, allFields)
      this.groups = this.groupField(this.logicalFields)
      this.fieldName = field.fieldName;
      this.options = field.options;
      this.currValue = this.options[0].value;
      this.show = true;
    },
    filterLogicalFields(field, allFields){
      let currIndex = allFields.findIndex(i => field == i);
      let logicalFields = allFields.filter((f, i) => {
        return (
          i > currIndex 
          && f.isSystem == 0 
        )
      })

      return cloneDeep(logicalFields)
    },
    cancel(){
      this.show = false;
    },
    submit(){
      this.$emit('submit', this.logicalFields)
      this.show = false;
    },
    choose(option){
      this.currValue = option.value;
    },
    // isSeparatorCheck: 是否是分割线选中，checkedAll：是否是分割线选中全部
    bindDep(target, isSeparatorCheck, checkedAll){
      let fieldName = this.fieldName;
      let dependencies = target.dependencies;
      if(!Array.isArray(dependencies[fieldName])) this.$set(dependencies, fieldName, [])
      
      let depValues = dependencies[fieldName];
      let index = depValues.indexOf(this.currValue);

      if (isSeparatorCheck) {
        return checkedAll ? (index < 0 ? depValues.push(this.currValue) : '') : depValues.splice(index, 1);
      }

      index < 0 ? depValues.push(this.currValue) : depValues.splice(index, 1)
    },
    isCheck(target){
      let fieldName = this.fieldName;
      let dependencies = target.dependencies;
      let depValues = dependencies[fieldName];

      return Array.isArray(depValues) && depValues.indexOf(this.currValue) >= 0;
    },
    // 获取当前分割线分组，不包含分割线
    getCurrentGroup(target) {
      let currentGroup = []
      this.groups.forEach(group => {
        group.forEach(f => {
          if (f.fieldName == target.fieldName) {
            currentGroup = group.filter(f => f.formType != 'separator')
          }
        })
      })
      return currentGroup
    },
    // 分割线分组的字段是否全部选中
    isCheckSeparator(target) {
      let checkedAll = true
      const currentGroup = this.getCurrentGroup(target)
      currentGroup.forEach(item => {
        if (!this.isCheck(item)) {
          checkedAll = false
        }
      })
      target.checkedAll = checkedAll
      return checkedAll
    },
    // 分割线不确定状态
    separatorIsIndeterminate(field) {
      if (!field.hasOwnProperty('isIndeterminate')) {
        field.isIndeterminate = true
      }
      const currentGroup = this.getCurrentGroup(field)
      let checkedCount = 0
      currentGroup.forEach(item => {
        if (this.isCheck(item)) {
          checkedCount++ 
        }
      })
      field.isIndeterminate = checkedCount > 0 && checkedCount < currentGroup.length
      return field.isIndeterminate
    },
    // 分割线选中
    separatorInput(target) {
      const currentGroup = this.getCurrentGroup(target)
      currentGroup.forEach(f => {
        this.bindDep(f, true, !target.checkedAll)
      })
      target.isIndeterminate = false
    },
    // 判断当前选项是否配置了显示逻辑
    hasDependencies(value) {
      let hasDependency = false
      this.logicalFields.forEach(f => {
        let dependencies = f.dependencies
        let depValues = dependencies[this.fieldName]
        if (Array.isArray(depValues) && depValues.indexOf(value) >= 0) {
          hasDependency = true
        }
      })
      return hasDependency
    },
    // 根据分割线分组
    groupField(fields) {
      let newArr = [];
      let preIndex = 0;
      
      fields.forEach((f, index, filterArr) => {
        if (f.formType === 'separator') {
          newArr.push(filterArr.slice(preIndex, index))
          preIndex = index
        }

        if (index === filterArr.length - 1) {
          newArr.push(filterArr.slice(preIndex))
        }
      })

      return newArr;
    },
    renderValueItem(option,index){   
      if(!option.value) return null;
      const className = ['logical-field-value', option.value == this.currValue ? 'logical-field-selected' : null];
      
      return (
        <div class={className} key={index} onClick={() => this.choose(option)}>
          <span>{option.value}</span>
          <i v-show={this.hasDependencies(option.value)} class="iconfont icon-fdn-related_task"></i>
        </div>
      )
    },
    renderTarget() {
      const domGroups = this.groups.map(group => {
        let currentGroupId = 0
        let title = group.filter(f => f.formType == 'separator').map(item => {
          // 表单设计器新增字段还没有id，改成fieldName判断
          currentGroupId = item.fieldName
          if (this.sectionState[currentGroupId] == undefined) {
            this.$set(this.sectionState, currentGroupId, true)
          }
          return this.renderTargetItem(item)
        })
        let items = group.filter(f => f.formType !== 'separator').map(item => this.renderTargetItem(item))

        return (
          <div class="view-group">
            {title}
            <div class="items-of-group">{
              (this.sectionState[currentGroupId] !== false) && items
            }</div>
          </div>
        )
      })

      return domGroups
    },
    renderTargetItem(field){
      if(field.isHidden == 1) return null
      const attrs = {
        nativeOn: {
          click: e => e.stopPropagation()
        }
      }

      if(field.formType == 'separator'){
        const cn = `iconfont icon-fdn-select ${!this.sectionState[field.fieldName] && 'reversal'}`;
        const currentGroup = this.getCurrentGroup(field)
        return (
          <div class="logical-field-target">
            <div class="logical-field-separator">
              <el-checkbox v-show={currentGroup.length} indeterminate={this.separatorIsIndeterminate(field)} value={this.isCheckSeparator(field)} onInput={() => this.separatorInput(field)} {...attrs} />
              {field.displayName}
              <i v-show={currentGroup.length} class={cn} onClick={() => this.toggleDisplay(field.fieldName)}></i>
            </div>
          </div>
        )
      }

      return (
        <div class="logical-field-target" key={field.fieldName} onClick={(e) => this.bindDep(field)}>
          <el-checkbox value={this.isCheck(field)} onInput={() => this.bindDep(field)} {...attrs}/>
          <p>{field.displayName}</p>
        </div>
      )
    },
    toggleDisplay(id) {
      this.sectionState[id] = !this.sectionState[id];
    },
  },
  render(h){
    const attrs = {
      props: {
        show: this.show,
        maskCloseable: false
      },
      on: {
        'update:show': val => this.show = val
      }
    }
    
    const tooltip = {
      directives: [{name: 'tooltip'}],
      domProps: {
        title: i18n.t('common.form.preview.select.title1')
      }
    }

    return (
      <base-modal class="logical-field-modal" width="640px" {...attrs}>
        <h3 slot="title">{i18n.t('common.form.tip.setVisionTip')} <i class="iconfont icon-question" {...tooltip}></i></h3>
        <div class="logical-field-panel">
          <h4 class="logical-field-panel-header">{i18n.t('common.form.preview.select.des1')}</h4>
          <div class="logical-field-panel-body">{ this.options.map((o,index) => this.renderValueItem(o,index)) }</div>
        </div>
        <div class="logical-field-panel">
          <h4 class="logical-field-panel-header">{i18n.t('common.form.preview.select.des2')}</h4>
          <div class="logical-field-panel-body">{ this.renderTarget() }</div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button  onClick={this.cancel}>{i18n.t('common.base.cancel')}</el-button>
          <el-button type="primary" onClick={this.submit}>{i18n.t('common.base.save')}</el-button>
        </div>
      </base-modal>
    )
  }
}

export default LogicalFieldModal;